<template>
  <div class="learn-view-info">
    <el-form
      type="flex"
      :model="questionInfoForm"
      :rules="questionInfoFormRules"
      :ref="questionInfoForm"
      class
      @submit.native.prevent
    >
      <el-form-item prop="title">
        <label style="color:red">*</label>
        <label>标题：</label>
        <el-input v-model="questionInfoForm.title" placeholder="请在这里输入标题" minlength="1" maxlength="64"></el-input>
      </el-form-item>
      <el-form-item prop="author">
        <label style="color:red">*</label>
        <label>作者：</label>
        <el-input v-model="questionInfoForm.author" :placeholder="this.$store.state.userinfo.name" maxlength="20"></el-input>
      </el-form-item>
      <p class="model-split-line"></p>
      <el-form-item prop="text">
        <label style="color:red">*</label>
        <label>正文</label>
        <quill-editor
          style="width:100%"
          ref="myQuillEditor"
          v-model="questionInfoForm.text"
          :options="util.intEditorOptions()"
          @blur="onEditorBlur($event)"
          @focus="onEditorFocus($event)"
          @change="onEditorChange($event)"
        ></quill-editor>
        <!-- 文件上传input 将它隐藏-->
        <el-upload
          :action="QINIUUPLOADURL"
          :before-upload="beforeAvatarUploadEditor"
          :data="qiniuDataEditor"
          :on-success="handleAvatarSuccessEditor"
          ref="uploadEditor"
          style="display:none"
        >
          <el-button size="small" type="primary" id="imgInput">点击上传</el-button>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <label>视频</label>
        <el-upload
          class="upload-demo"
          drag
          :action="QINIUUPLOADURL"
          :multiple="false"
          ref="videoUpload"
          :data="dryVideoQiniuData"
          :on-success="function(res, file, fileList) {return handleAvatarSuccess(res, file, fileList, 'dryVideoQiniuData')}"
          :on-remove="function(file, fileList) {return handleRemovePic(file, fileList, 'dryVideoQiniuData')}"
          :on-error="function(res) {return handleError(res, 'dryVideoQiniuData')}"
          :before-upload="function(file){return beforeAvatarUpload(file, 'dryVideoQiniuData')}"
          :file-list="dryVideoQiniuData.fileList"
          :limit="1"
          :on-exceed="function(files, fileList) {return handleExceed(files, fileList, 'dryVideoQiniuData')}"
          accept=".avi, .rmvb, .wmv, .mp4"
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">
            将文件拖到此处，或
            <em>点击上传</em>
          </div>
          <div class="el-upload__text">支持扩展名：.avi、.rmvb、.wmv、.mp4</div>
        </el-upload>
        <video style="display: none;" controls="controls" id="uploadVideo" width="200" height="100"></video>
      </el-form-item>
      <p class="model-split-line"></p>
      <el-form-item prop="learningTime">
        <label style="color:red">*</label>
        <label>设置学习时长</label>
        <el-input-number
          style="margin-left:56%"
          v-model="questionInfoForm.learningTime"
          controls-position="right"
          @change="learnTimeChange"
          :min="0"
          :max="200"
        ></el-input-number>
        <label>分钟</label>
      </el-form-item>
      <el-form-item prop="label">
        <label style="color:red">*</label>
        <label>添加标签</label>
        <select-label :selectVal="questionInfoForm.label" ref="selectLabel"></select-label>
      </el-form-item>
      <p class="model-split-line"></p>
      <el-form-item>
        <label>添加封面</label>
        <el-upload
          :action="QINIUUPLOADURL"
          :multiple="false"
          ref="upload"
          list-type="picture-card"
          :data="dryPicQiniuData"
          :on-success="function(res, file, fileList) {return handleAvatarSuccess(res, file, fileList, 'dryPicQiniuData')}"
          :on-remove="function(file, fileList) {return handleRemovePic(file, fileList, 'dryPicQiniuData')}"
          :on-error="function(res) {return handleError(res, 'dryPicQiniuData')}"
          :before-upload="function(file){return beforeAvatarUpload(file, 'dryPicQiniuData')}"
          :on-preview="$imgPreview"
          :file-list="dryPicQiniuData.fileList"
          :limit="1"
          :on-exceed="function(files, fileList) {return handleExceed(files, fileList, 'dryPicQiniuData')}"
          accept="image/gif, image/jpeg, image/jpg, image/bmp, image/png"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
      </el-form-item>
      <p class="model-split-line"></p>
      <el-form-item prop="originalLink">
        <label>原文链接</label>
        <el-input v-model="questionInfoForm.originalLink" placeholder="如果您的文章是引用他人，请务必在此添加原文链接"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer" style="float: right;margin-bottom:20px;">
      <el-button @click.stop="closeFun">取 消</el-button>
      <el-button type="primary" @click="saveLeran(questionInfoForm)">保 存</el-button>
    </span>
  </div>
</template>
<script>
import util from '@/utils/util'
import { qnToken } from '@/api/api'
import SelectLabel from '../../Examination/Common/SelectLabel'
import {
  selectLearningMaterialsList,
  deleteLearningMaterials,
  getLearningMaterialsDetail,
  saveLearningMaterials,
} from '@/api/rdLearnOrg'
export default {
  name: 'LearnAdd',

  props: {
    oldInfo: {
      type: Object,
      default() {
        return {}
      },
    },
    closeFun: {
      type: Function,
      required: true,
    },
  },
  components: {
    SelectLabel,
  },
  mounted() {
    // 为图片ICON绑定事件  getModule 为编辑器的内部属性
    this.$refs.myQuillEditor.quill
      .getModule('toolbar')
      .addHandler('image', this.imgHandler)
    this.$refs.myQuillEditor.quill
      .getModule('toolbar')
      .addHandler('video', this.videoHandler) // 为视频ICON绑定事件
  },
  data() {
    // let nameRule1 = (rule, value, callback) => {//相关链接正则表达式
    //     let regExp = /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/;
    //     if (regExp.test(value) === false) {
    //         callback(new Error('请输入正确的链接'));
    //     } else {
    //         callback();
    //     }
    // }
    return {
      util: util, //富文本
      //新增
      questionInfoForm: {
        id: '',
        orgId: '',
        title: '',
        author: '',
        videoUrl: '',
        coverUrl: '',
        learningTime: '',
        label: '',
        originalLink: '',
        text: '',
      },
      editForm: {
        id: 0,
        orgId: '' /*this.$store.state.userinfo.org.id*/,
        name: '',
        level: '',
        type: '',
        text: '',
        taskContent: '',
        membersStr: '',
      },
      questionInfoFormRules: {
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        text: [{ required: true, message: '请输入正文', trigger: 'blur' }],
        learningTime: [
          { required: true, message: '请设置学习时间', trigger: 'blur' },
        ],
      },
      qiniuDataEditor: {
        //富文本编辑器相关  预案流程
        token: '',
        key: '',
        fileList: [],
      },
      // 视频
      dryVideoQiniuData: {
        key: '',
        fileList: [],
      },
      dryPicQiniuData: {
        key: '',
        fileList: [],
      },
      learnTime: 0, //建议学习时长
      firstPic: 11,
      PicTime: 0,
      PicOld: 0,
      videoTime: 0,
      textTime: 0,
      oldtext: 0,
    }
  },
  created() {
    let that = this
    that.getToken() //获取封面token
  },
  methods: {
    //保存学习资料
    saveLeran(questionInfoForm) {
      let that = this
      that.dialogVisible = false
      that.$refs[questionInfoForm].validate((valid) => {
        if (valid) {
          let parames = that.questionInfoForm
          // 图片
          parames.coverUrl = util.ilinkArrHandle
            .getqiniuPicUrlArr(that.dryPicQiniuData.fileList)
            .toString()
          // 视频
          parames.videoUrl = util.ilinkArrHandle
            .getqiniuPicUrlArr(that.dryVideoQiniuData.fileList)
            .toString()
          parames.id = that.oldInfo.id || ''
          ;(parames.author =
            that.questionInfoForm.author || this.$store.state.userinfo.name),
            (parames.label = that.$refs['selectLabel']
              .getSelectLabel()
              .join(','))
          parames.learningTime = that.questionInfoForm.learningTime
          if (that.$refs['selectLabel'].getSelectLabel().join(',') == '') {
            that.$message.error('请选择标签')
            return false
          } else {
            saveLearningMaterials(parames).then((res) => {
              if (res.status === 200) {
                // 提交成功
                that.$message.success('保存成功！')
                setTimeout(function () {
                  that.closeFun(true)
                }, 1000)
              }
            })
          }
        } else {
          return false
        }
      })
      // let parames={
      //     id: that.oldInfo.id || '',
      //     //orgId: this.$store.state.userinfo.organizationIds,
      //     title: that.questionInfoForm.title,
      //     author:that.questionInfoForm.author || this.$store.state.userinfo.name,
      //     text: that.questionInfoForm.text,
      //     videoUrl:util.ilinkArrHandle.getqiniuPicUrlArr(that.dryVideoQiniuData.fileList).toString(),
      //     coverUrl: util.ilinkArrHandle.getqiniuPicUrlArr(that.dryPicQiniuData.fileList).toString(),
      //     learningTime:that.questionInfoForm.learningTime,
      //     label:that.$refs['selectLabel'].getSelectLabel().join(','),
      //     originalLink:that.questionInfoForm.originalLink
      // }
      // saveLearningMaterials(parames).then(res => {
      //     if(res.status === 200) {
      //         // 提交成功
      //         that.$message.success('保存成功！')
      //         setTimeout(function(){
      //             that.closeFun(true)
      //         }, 1000)
      //         that.questionInfoForm={}
      //     }
      // })
    },
    handleCurrentChange(currentPage) {},
    handleSizeChange(pageSize) {},
    handleSelect() {
      //处理添加标签
    },
    learnTimeChange(value) {
      //检测时长改变
    },
    //--------------------BEGIN  富文本编辑器相关------------------------------//
    beforeAvatarUploadEditor: function (file) {
      //重命名和校验
      this.loading = true
      const suffix = file.name.split('.')
      const ext = suffix.splice(suffix.length - 1, 1)[0]
      var fielLocal = file.name.split('.')
      var fielType = '.' + fielLocal[fielLocal.length - 1]
      var fielLocalName = fielLocal[0]
      this.qiniuDataEditor.key = 'ilink_' + new Date().getTime() + fielType
    },
    handleAvatarSuccessEditor: function (res, file, fileList) {
      //上传成功
      this.loading = false
      let vm = this
      let url = QINIUUPLOADURL.indexOf('uploadFile')>-1? res.data:QINIUPATH+res.key
      if (url != null && url.length > 0) {
        // 将文件上传后的URL地址插入到编辑器文本中
        let value = url
        vm.qiniuDataEditor.fileList = vm.$refs.myQuillEditor.quill.getSelection()
        vm.$refs.myQuillEditor.quill.insertEmbed(
          vm.qiniuDataEditor.fileList !== null
            ? vm.qiniuDataEditor.fileList.index
            : 0,
          vm.uploadType,
          value
        ) // 调用编辑器的 insertEmbed 方法，插入URL
      } else {
        this.$message.error('上传失败')
      }
      this.$refs['uploadEditor'].clearFiles() // 插入成功后清除input的内容
    },
    // 点击图片ICON触发事件
    imgHandler(state) {
      this.addRange = this.$refs.myQuillEditor.quill.getSelection()
      if (state) {
        let fileInput = document.getElementById('imgInput')
        fileInput.click() // 加一个触发事件
      }
      this.uploadType = 'image'
    },
    // 点击视频ICON触发事件
    videoHandler(state) {
      this.addRange = this.$refs.myQuillEditor.quill.getSelection()
      if (state) {
        let fileInput = document.getElementById('imgInput')
        fileInput.click() // 加一个触发事件
      }
      this.uploadType = 'video'
    },
    // 编辑器光标离开 将编辑器内容发射给父组件
    onEditorBlur(editor) {
      //时长 = 视频长度 + 总字数/500 * 60（秒）+ 图片的时长(推荐学习时长算法)
      let str = '<img src='
      let html = this.questionInfoForm.text //this.editForm.text
      let n = html.split(str).length - 1 //添加图片的张数
      let picTime = 0
      let text = editor.getText()

      if (this.PicOld != n) {
        if (n < 10) {
          this.PicTime = this.firstPic
          this.firstPic--
          this.PicOld = n
          this.learnTime = this.learnTime + this.PicTime / 60
        } else {
          this.PicTime = 3
          this.PicOld = n
          this.learnTime = this.learnTime + this.PicTime / 60
        }
      }
      if (text.length - 1) {
        let a = (text.length - 1 - this.oldtext) / 500
        this.learnTime = this.learnTime + a
        this.oldtext = text.length - 1
      }
      // this.$emit('getValue', this.editForm.text)
    },
    // 编辑器获得光标
    onEditorFocus(editor) {
      editor.enable(true) // 实现达到上限字符可删除
    },
    // 编辑器文本发生变化
    onEditorChange({ editor, html, text }) {
      let textLength = text.length
      // if (textLength > 10000) {
      //     this.$message.error('最多输入10000个字符');
      //     editor.enable(false)
      // }
      // this.$emit('getValue', this.editForm.text )
    },
    // 清除编辑器内容
    callMethod() {
      this.questionInfoForm.text = ''
    },
    //--------------------END  富文本编辑器相关------------------------------//
    //--------------------BEGIN  上传封面相关------------------------------//
    getToken() {
      //上传之前获取 token
      let that = this
      qnToken({}).then((result) => {
        this.qiniuDataEditor.token = result.data
        $.extend(this.dryVideoQiniuData, this.qiniuDataEditor)
        $.extend(this.dryPicQiniuData, this.qiniuDataEditor)
        that.$nextTick(() => {
          // 如果有历史数据
          if (Object.keys(that.oldInfo).length > 0) {
            for (var key in that.questionInfoForm) {
              that.questionInfoForm[key] = that.oldInfo[key]
            }
            // 设置短视频
            that.oldInfo.videoUrl
              ? $.each(that.oldInfo.videoUrl.split(','), (index, url) => {
                  let arr = url.split('/')
                  that.dryVideoQiniuData.fileList = []
                  that.dryVideoQiniuData.fileList.push({
                    name: arr[arr.length - 1],
                    url: url,
                  })
                })
              : ''

            // 设置图片回显
            that.oldInfo.coverUrl
              ? $.each(that.oldInfo.coverUrl.split(','), (index, url) => {
                  let arr = url.split('/')
                  that.dryPicQiniuData.fileList = []
                  that.dryPicQiniuData.fileList.push({
                    name: arr[arr.length - 1],
                    url: url,
                  })
                })
              : ''
          }
        })
      })
    },
    // 判断短视频时长
    judgeVideoDuration() {
      let that = this
      return new Promise(function (resolve, reject) {
        let dom = document.getElementById('uploadVideo')
        dom.oncanplaythrough = (e) => {
          // if(e.target.duration > 60) {
          //     that.$message.error("视频长度最多60秒")
          //     reject()
          // } else {
          // 上传视频
          that.videoTime = e.target.duration
          resolve()
          // }
        }
      })
    },
    beforeAvatarUpload(file, type, obj) {
      //重命名和校验
      var fielLocal = file.name.split('.')
      var fielType = '.' + fielLocal[fielLocal.length - 1]
      var fielLocalName = fielLocal[0]
      this[type].key = 'ilink' + '_' + new Date().getTime() + fielType
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt20M = file.size / 1024 / 1024 < 20
      if (type === 'dryVideoQiniuData') {
        let video = file
        let url = URL.createObjectURL(video)
        let dom = document.getElementById('uploadVideo')
        dom.src = url
        return this.judgeVideoDuration()
      } else {
        if (!isJPG && !isPNG) {
          this.$message.error('图片只能是 JPG/PNG 格式!')
          return false
        }
        if (!isLt20M) {
          this.$message.error('图片大小不能超过 20MB!')
          return false
        }
      }
    },
    handleAvatarSuccess: function (res, file, fileList, type, obj) {
      //上传成功
      if (obj) {
        obj[type].fileList = fileList
      } else {
        this[type].fileList = fileList
      }
    },
    handleRemovePic: function (file, fileList, type, obj) {
      //删除成功
      let that = this
      that.questionInfoForm.learningTime -= 1
      // that.videoTime = e.target.duration
      if (obj) {
        obj[type].fileList = fileList
      } else {
        this[type].fileList = fileList
      }
    },
    handleError: function (res, type) {
      this.$message({
        message: '上传失败',
        duration: 2000,
        type: 'warning',
      })
    },
    handleExceed(files, fileList, type) {
      //文件超出个数限制时的钩子
      if (type === 'dryVideoQiniuData') {
        this.$message.warning(
          `${TYPEMAP[type]}最多只能上传1个，如需重新上传请先删除原先视频`
        )
      } else if (type === 'dryPicQiniuData') {
        this.$message.warning(`只能上传一张图片！`)
      }
    },
    //--------------------end  上传封面相关结束------------------------------//
  },
  watch: {
    learnTime(val, oldVal) {
      let that = this
      if (val && val !== oldVal) {
        that.questionInfoForm.learningTime = Math.ceil(that.learnTime)
      }
    },
    videoTime(val, oldVal) {
      let that = this
      if (val && val !== oldVal) {
        that.questionInfoForm.learningTime =
          that.questionInfoForm.learningTime + Math.ceil(that.videoTime / 60)
      }
    },
  },
}
</script>
<style lang="scss" scoped>
.model-split-line {
  .type-item-wrap {
    line-height: 40px;
    .type-title {
      color: #409eff;
      font-size: 16px;
      font-weight: bold;
      text-align: center;
    }
  }
}
.model-split-line {
  margin-top: 10px;
  border-bottom: 1px solid #dcdfe6;
  margin-bottom: 10px;
}
.learn-view-info {
  padding: 0px 100px 20px 100px;
}
</style>
<style lang="scss">
.ql-video {
  display: none !important;
}
</style>
